/**
 * Project Name:hyh-web
 * File Name:SpringConfigurerAdapter.java
 * Package Name:com.hyh.configuration
 * Date:2018年8月31日下午2:36:56
 *
*/

package com.hyh.configuration;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.hyh.annotation.SpringHandlerInterceptor;

/**
 * ClassName:SpringConfigurerAdapter Reason: TODO ADD REASON. Date: 2018年8月31日
 * 下午2:36:56
 * 
 * @author huangyihao
 * @version
 * @see
 */
@Configuration
@EnableWebMvc
public class SpringConfigurerAdapter implements WebMvcConfigurer {

	@Autowired
	private List<HandlerInterceptor> handlerInterceptors;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		if (handlerInterceptors == null || handlerInterceptors.isEmpty()) {
			return;
		}
		Collections.sort(handlerInterceptors, (a, b) -> getInterceptorOrder(a) - getInterceptorOrder(b));

		for (HandlerInterceptor handlerInterceptor : handlerInterceptors) {
			SpringHandlerInterceptor annotation = AnnotationUtils.findAnnotation(handlerInterceptor.getClass(),
					SpringHandlerInterceptor.class);
			
			InterceptorRegistration registration = registry.addInterceptor(handlerInterceptor);
			if (annotation == null) {
				continue;
			}

			registration.addPathPatterns(annotation.includePatterns());
			registration.excludePathPatterns(annotation.excludePatterns());
		}

		WebMvcConfigurer.super.addInterceptors(registry);
	}

	private int getInterceptorOrder(HandlerInterceptor o) {
		SpringHandlerInterceptor annotation = AnnotationUtils.findAnnotation(o.getClass(), SpringHandlerInterceptor.class);
		if (annotation == null) {
			return 0;
		}
		return annotation.order();
	}
	
	private static final String ORIGINS[] = { "*" };
	
	private static final String METHODS[] = { "GET", "POST", "PUT", "DELETE" };
	 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        		.allowedOrigins(ORIGINS)
        		.allowCredentials(true)
        		.allowedMethods(METHODS)
                .maxAge(3600);
    }

}
